package com.shuai.frame.fault.retry.impl;

import com.github.rholder.retry.*;
import com.shuai.frame.fault.retry.RetryStrategy;
import com.shuai.frame.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author bxs
 * @version 1.0
 * @Date 2024/7/28
 * 固定时间重试
 */
@Slf4j
public class FixedIntervalRetryStrategyImpl implements RetryStrategy {
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)    // 如果抛出异常就重试
                .withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS))   // 每隔3s重试一次
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))   // 重试三次仍不成功则放弃重试
                .withRetryListener(new RetryListener() {    // 重试监听器，比如可以配置如果重试超过指定次数仍然没有成功怎么办
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.info("第{}次重试", attempt.getAttemptNumber());
                    }
                })
                .build();
        return retryer.call(callable);
    }
}
